import useMessage from "@/hooks/useMessage";
import { Form, Button, Input, FormInstance } from "antd";
import React, { useEffect, useRef, useState } from "react";
import { addPermissionApi, getPermissionDetailApi, updatePermissionApi } from "@/api/modules/user";
import { User } from "@/api/interface";

interface PropsType {
	type?: string;
	permissionId?: number;
	onComfirm?: () => void;
}

const PermissionAdd: React.FC<PropsType> = props => {
	const { type, onComfirm, permissionId } = props;
	const { contextHolder, success } = useMessage();

	const [permissionDetail, setPermissionDetail] = useState<any>({});

	const getPermissionDetail = async () => {
		const res = await getPermissionDetailApi(permissionId!);
		if (res.code === 200) {
			setPermissionDetail(res.data);
		}
	};

	const formRef = useRef<FormInstance | null>(null);

	const onFinish = async (permission: User.Permission) => {
		if (type && permissionId) {
			updatePermissionApi({ ...permission, id: permissionId });
		} else {
			addPermissionApi(permission);
		}
		formRef.current?.setFieldsValue({
			name: "",
			action: ""
		});
		onComfirm && onComfirm();
		success("发布成功");
	};

	useEffect(() => {
		if (type) {
			getPermissionDetail();
		}
	}, [permissionId]);

	useEffect(() => {
		formRef.current?.resetFields();
		return () => {
			formRef.current?.setFieldsValue({
				name: "",
				action: ""
			});
		};
	}, [permissionDetail]);

	return (
		<div>
			{contextHolder}
			<Form
				ref={formRef}
				labelCol={{ span: 4 }}
				wrapperCol={{ span: 16 }}
				layout="horizontal"
				onFinish={onFinish}
				initialValues={permissionDetail}
			>
				<Form.Item label="权限" rules={[{ required: true }]} name="name">
					<Input />
				</Form.Item>
				<Form.Item label="行为" rules={[{ required: true }]} name="action">
					<Input />
				</Form.Item>
				<Form.Item wrapperCol={{ offset: 4 }}>
					<Button htmlType="submit" type="primary">
						提交
					</Button>
				</Form.Item>
			</Form>
		</div>
	);
};

export default PermissionAdd;
